import ourPreviewImage from '../../../modules/previewImage';

function exclusive(btnList, methodName) {
    let keyShareIndex = -1;
    btnList.some((item, index) => {
        if (item.name === methodName) {
            keyShareIndex = index;
            return true;
        }
        return false;
    });
    if (keyShareIndex !== -1) {
        btnList.splice(keyShareIndex, 1);
    }
    return btnList;
}

function getBtnList(share, btnList, hasQr) {
    if (WPT.os.device == 'wechat') {
        // 微信
        btnList = btnList || [{ name: '二维码' }, { name: '一键分享' }, { name: '复制链接' }];
        if (!share.qLink || share.pics.length < 1 || window.__wxjs_environment === 'miniprogram') {
            btnList = exclusive(btnList, '一键分享');
        }
        if (!hasQr) {
            btnList = exclusive(btnList, '二维码');
        }
    } else if (WPT.os.dyXcx) {
        // 头条、抖音小程序
        btnList = [{ name: '复制链接' }];
    } else if (WPT.os.device == 'weibo') {
        // 微博
    } else {
        btnList = btnList || [
            { name: '二维码' },
            { name: '一键分享' },
            { name: '微博' },
            { name: 'QQ' },
            { name: '百度贴吧' },
            { name: '豆瓣' },
        ];
        if (!share.qLink || share.pics.length < 1) {
            btnList = exclusive(btnList, '一键分享');
        }
        if (!hasQr || !share.link || !share.desc || !share.imgUrl) {
            btnList = exclusive(btnList, '二维码');
        }
    }
    return btnList;
}

function keyShare(e, share) {
    e.preventDefault && e.preventDefault();
    const matches = share.link.match(/(\/uri)?\/(\w{16})($|\?)/);
    const saleUri = matches && matches[2] ? matches[2] : '';
    let link = share.link;
    if (!WPT.Util.getQueryString('showShare')) {
        link = WPT.Util.addUrlParam(link, 'showShare', 1);
    }
    if (saleUri) {
        $.ajax({
            url: `${WPT.API_HOST}app/v1.0/shortlink/get-code`,
            xhrFields: {
                withCredentials: true,
            },
            crossDomain: true,
            data: {
                url: btoa(link),
                saleUri: btoa(saleUri),
            },
            type: 'GET',
            dataType: 'json',
            success(data) {
                WPT.Modal.close(false);
                WPT.Modal.confirm(
                    `<img src='${WPT.CDNURL}static/20170804db6688d4-6734-4199-b342-9c16f2ff7389-W420H630/w/640' width='100%' />`,
                    {
                        btnName: '打开App',
                        callback: () => {
                            WPT.openApp(link, `$${data.data.code}$`);
                        },
                    }
                );
            },
        });
    } else {
        WPT.Modal.close(false);
        WPT.Modal.confirm(
            `<img src='${WPT.CDNURL}static/20170804db6688d4-6734-4199-b342-9c16f2ff7389-W420H630/w/640' width='100%' />`,
            {
                btnName: '打开App',
                callback: () => {
                    WPT.openApp(link);
                },
            }
        );
    }
}

function qrFunction(e, share, shareName, previewImg) {
    e.preventDefault && e.preventDefault();
    const { location } = window;
    if (location.pathname == '/webApp/promotion/doubleFlow') {
        WPT.showPage(`/webApp/promotion/doubleFlow/shopShareQr?img=${share.qrcodeImgUrl}`);
        return;
    }
    let link = share.link.replace(/((^\/\/|^https?:\/\/|^\/\/))/, `${location.protocol}//`);
    link = WPT.Util.addUrlParam(link, 'r', 'qrCode');
    let params = {
        link: encodeURIComponent(link),
        desc: share.desc.replace(/[\s]/g, ''),
        imgUrl: share.imgUrl ? share.imgUrl.replace(/\/w\/\d+$/, '') : '',
    };
    const linkArr = location.pathname.split('/');
    const articleUri = linkArr[linkArr.length - 1];
    if (linkArr.splice(0, linkArr.length - 1).join('/') == '/webApp/article/newDetail') {
        params = {
            type: 14,
            articleUri,
            link: location.href,
        };
    }
    WPT.postData(WPT.Util.handleApi('/v1.0/qr/share'), params, res => {
        if (res.code != 0) {
            WPT.Modal.alert(res.msg);
            return;
        }
        const shareQRUrl = `${res.data.shareQRUrl}${res.data.shareQRUrl.indexOf('?') == -1 ? '?' : '&'}t=${Date.now()}`;
        const preview = previewImg || ourPreviewImage;
        WPT.Modal.close(false);
        preview({
            current: shareQRUrl,
            urls: [shareQRUrl],
        });
    });
}

function copyLink(e, share) {
    e.preventDefault && e.preventDefault();
    const { location } = window;
    const query = WPT.Util.query();
    const shareUrl = share.link
        ? WPT.Util.urlAddQuery(share.link, { from: 'timeline' })
        : WPT.Util.urlAddQuery(`${location.origin}${location.pathname}`, {
            from: 'timeline',
            ...query,
        });

    WPT.Util.copyToClipboard(shareUrl);
    WPT.Modal.tips('复制成功');
}

function openPage(e, share, shareName) {
    const encodeLink = encodeURIComponent(share.link);
    let linkUrl = '';
    switch (shareName) {
        case '微博': {
            linkUrl = `//service.weibo.com/share/share.php?url=${encodeLink}&searchPic=true&appkey=400447710&title=${
                share.title
            }&pic=${share.pics.join('||')}`;
            break;
        }
        case 'QQ': {
            linkUrl = `//connect.qq.com/widget/shareqq/index.html?url=${encodeLink}&title=${share.title}&desc=${share.desc}&summary=${share.summary}&pics=${share.pics[0]}`;
            break;
        }
        case '百度贴吧': {
            linkUrl = `//tieba.baidu.com/f/commit/share/openShareApi?url=${encodeLink}&title=${share.title}&desc=${
                share.desc
            }&pic=${encodeURIComponent(share.pics[0])}`;
            break;
        }
        case '豆瓣': {
            linkUrl = `//www.douban.com/recommend/?url=${encodeLink}&title=${share.title}&text=${share.summary}`;
            break;
        }
        default: {
            linkUrl = '';
        }
    }
    window.open(linkUrl, '_blank');
}

const shareIconMap = new Map([
    [
        '二维码',
        {
            url: 'https://cdn.weipaitang.com/static/202004092cd38c58-17d1-8c5817d1-1853-0f8ea9eaeabc-W100H100',
            event: qrFunction,
        },
    ],
    [
        '一键分享',
        {
            url: 'https://cdn.weipaitang.com/static/2020040977475339-b896-5339b896-75aa-297c6befdce9-W100H100',
            event: keyShare,
        },
    ],
    [
        '微博',
        {
            url: 'https://cdn.weipaitang.com/static/20200409061ae0f4-6066-e0f46066-ff5d-b1d37b14932c-W100H100',
            event: openPage,
        },
    ],
    [
        'QQ',
        {
            url: 'https://cdn.weipaitang.com/static/2020040936510107-6dbf-01076dbf-9c80-0206b1afd23b-W100H100',
            event: openPage,
        },
    ],
    [
        '百度贴吧',
        {
            url: 'https://cdn.weipaitang.com/static/2020040942da7476-8c9a-74768c9a-4034-b3e004a9881e-W100H100',
            event: openPage,
        },
    ],
    [
        '豆瓣',
        {
            url: 'https://cdn.weipaitang.com/static/202004090c92b304-9ea6-b3049ea6-d13a-776ba6dc4121-W100H100',
            event: openPage,
        },
    ],
    [
        '复制链接',
        {
            url: 'https://cdn.weipaitang.com/static/20200409484ade14-316d-de14316d-df73-17b975562406-W100H100',
            event: copyLink,
        },
    ],
]);

export { shareIconMap, getBtnList };
